简单工厂【Simple Factory】
实例
// 操作类
abstract class Operation
{
protected $a = 0;
protected $b = 0;
public function setA($a)
{
$this->a = $a;
}
public function setB($b)
{
$this->b = $b;
}
abstract protected function getResult();
}
// 加
class Add extends Operation
{
public function getResult()
{
return $this->a + $this->b;
}
}
// 减
class Sub extends Operation
{
public function getResult()
{
return $this->a - $this->b;
}
}
// 乘
class Mul extends Operation
{
public function getResult()
{
return $this->a * $this->b;
}
}
// 除
class Div extends Operation
{
public function getResult()
{
return $this->a / $this->b;
}
}
// 操作工厂类
class OperationFactory
{
public static function createOperation($args)
{
switch ($args) {
case '+':
$operation = new Add();
break;
case '-':
$operation = new Sub();
break;
case '*':
$operation = new Mul();
break;
case '/':
$operation = new Div();
break;
}
return $operation;
}
}
$operation = OperationFactory::createOperation('+');
$operation->setA(1);
$operation->setB(2);
echo $operation->getResult() . PHP_EOL; // 3
interface ProductInterface
{
public function showProductInfo();
}
class ProductA implements ProductInterface
{
public function showProductInfo()
{
echo 'This is product A', PHP_EOL;
}
}
class ProductB implements ProductInterface
{
public function showProductInfo()
{
echo 'This is product B', PHP_EOL;
}
}
class ProductFactory
{
public static function factory($ProductType)
{
$ProductType = 'Product' . strtoupper($ProductType);
if (class_exists($ProductType)) {
return new $ProductType();
} else {
throw new Exception("Error Processing Request", 1);
}
}
}
// 这里需要一个产品型号为 A 的对象
try {
$x = ProductFactory::factory('A'); // This is product A
} catch (Exception $e) {
}
$x->showProductInfo(); // This is product A
// 这里需要一个产品型号为 B 的对象
try {
$o = ProductFactory::factory('B'); // This is product B
} catch (Exception $e) {
}
$o->showProductInfo(); // This is product B
核心方法论
- 封装 (Encapsulation): 将数据(属性)和操作数据的方法(行为)捆绑在一起,隐藏内部细节。
- 体现:
Operation基类封装了$a和$b属性及其设置方法。
- 体现:
- 继承 (Inheritance): 子类继承父类的属性和方法。
- 体现:
Add,Sub,Mul,Div继承自抽象类Operation。
- 体现:
- 多态 (Polymorphism): 不同的子类对象对父类或接口定义的同一方法有不同的实现。
- 体现:
Add,Sub,Mul,Div都实现了getResult(),但返回不同运算结果。
- 体现:
设计目标
- 高内聚 (High Cohesion): 一个模块或类只负责完成一项任务。
- 体现: 每个操作类(
Add,Sub等)只专注于实现自己的运算逻辑。
- 体现: 每个操作类(
- 低耦合 (Low Coupling): 模块或类之间的依赖关系降到最低。
- 体现: 简单工厂模式 (
OperationFactory) 将客户端代码与具体操作类(Add,Sub等)解耦。客户端只需知道工厂和抽象Operation即可。
- 体现: 简单工厂模式 (
复用原则
- 复用而非复制: 强调通过继承、多态等 OOD 机制实现代码复用,而不是简单的复制粘贴。
示例中的模式
两个示例均体现了简单工厂模式 (Simple Factory):
- 第一个示例 (
OperationFactory): 通过switch语句集中创建不同的运算对象,将对象的实例化和客户端使用分离开来。 - 第二个示例 (
ProductFactory): 利用反射/动态类名(class_exists和new $ProductType())来创建不同的产品对象,进一步降低了工厂内的逻辑判断复杂度。